package com.ruoyi.framework.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 描述 MyBatisPlus自动填充创建和更新的时间和人员
 * 作者 ZhangPing
 * 创建时间 2023/9/7 13:42
 */
@Component
public class MyBatisPlusFillConfig implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        if (metaObject.getValue("createTime") == null) {
            this.setFieldValByName("createTime", new Date(), metaObject);
        }
        if (metaObject.getValue("createBy") == null) {
            this.setFieldValByName("createBy", SecurityUtils.getAuthentication() == null ? "1" : SecurityUtils.getUserId().toString(), metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject.getValue("updateTime") == null) {
            this.setFieldValByName("updateTime", new Date(), metaObject);
        }
        if (metaObject.getValue("updateBy") == null) {
            this.setFieldValByName("updateBy", SecurityUtils.getAuthentication() == null ? "1" : SecurityUtils.getUserId().toString(), metaObject);
        }
    }
}
